package Reseau;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JEditorPane;

import IHM.UI;
import IHM.pPartie;
import Moteur.CalculTrajectoires;
import Moteur.Mouvement;
import Objets.Bille;
import Utils.Parametres;

public class FluxReception extends FluxdeString implements Runnable {

	Socket socket;
	long dateLastPing0=-1;
	long dateLastPing1;
	int ping;
	private boolean running = true;
	private pPartie ppartie;
	public FluxReception(Socket socket,pPartie ppartie){
		this.socket = socket;
		this.ppartie = ppartie;
		new Thread(this).start();
		new Thread(){
			public void run(){
				while(running){
					if(System.currentTimeMillis()-dateLastPing1-Parametres.deltaTenvoiUDP>9999){
						UI.supprPanelActuel();
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
	public int getPing(){
		return ping;
	}
	public void stop(){
		running = false;
	}
	public void run() {
		while(running){
			try {
				String message = super.reception(socket);
				if(message.split("//",2)[0].equals("CHAT"))ppartie.afficherMessageln("Lui : "+message.split("//",2)[1]);
				else if(message.split("//",2)[0].equals("vV")){
					ArrayList<Bille> listeBilles = ppartie.getBillard().getListeBilles();
					listeBilles.get(0).setLastvXY((float[])Parametres.readSerializedObjectFromString(message.split("//",2)[1]));
					new CalculTrajectoires(ppartie,new Mouvement(ppartie,ppartie.getBillard().getListeBilles())).start();
				}
				else if(message.split("//",2)[0].equals("PLACEBLANCHE")){
					Bille blanche = ppartie.getBillard().getListeBilles().get(0);
					float[] nxy = (float[])Parametres.readSerializedObjectFromString(message.split("//",2)[1]);
					blanche.setXyEcran(nxy);
					blanche.setLastXY(nxy);
					blanche.setPochee(false);
					
					ppartie.repaint();
				}
				else if(message.equals("ping")){
					if (dateLastPing0==-1){
						dateLastPing0=dateLastPing1=System.currentTimeMillis();
					}
					else{
						long dateLastPing = System.currentTimeMillis();
						ping = (int) ((dateLastPing-dateLastPing1)-Parametres.deltaTenvoiUDP);
						dateLastPing0=dateLastPing1;
						dateLastPing1=dateLastPing;
					}
				}
				Thread.sleep(100);
			} catch (Exception e) {
			}
		}
	}


}
